import 'package:beng_beng_utils/utils/log/BBLogUtils.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences/util/legacy_to_async_migration_util.dart';

import '../ToastUtils.dart';
import '../log/BBLogType.dart';

extension ObjectExt on Object {
  bool save(String key) {
    SharedPreferences sp = GetSp.theSpInstance!;
    if (this is String) {
      sp.setString(key, this as String);
    } else if (this is bool) {
      sp.setBool(key, this as bool);
    } else if (this is int) {
      sp.setInt(key, this as int);
    } else if (this is double) {
      sp.setDouble(key, this as double);
    } else if (this is List<String>) {
      sp.setStringList(key, this as List<String>);
    } else {
      return false;
    }
    return true;
  }
}

extension GetSpExt on String {
  String getString({String defaultValue = ""}) {
    SharedPreferences sp = GetSp.theSpInstance!;
    return sp.getString(this) ?? defaultValue;
  }

  bool getBool({bool defaultValue = false}) {
    SharedPreferences sp = GetSp.theSpInstance!;
    return sp.getBool(this) ?? defaultValue;
  }

  int getInt({int defaultValue = 0}) {
    SharedPreferences sp = GetSp.theSpInstance!;
    return sp.getInt(this) ?? defaultValue;
  }

  double getDouble({double defaultValue = 0.0}) {
    SharedPreferences sp = GetSp.theSpInstance!;
    return sp.getDouble(this) ?? defaultValue;
  }

  List<String> getStringList({List<String> defaultValue = const []}) {
    SharedPreferences sp = GetSp.theSpInstance!;
    return sp.getStringList(this) ?? defaultValue;
  }
}

class GetSp {
  static SharedPreferences? theSpInstance;

  static Future<SharedPreferences> initSp() async {
    if (theSpInstance == null) {
      theSpInstance = await SharedPreferences.getInstance();
      const SharedPreferencesOptions sharedPreferencesOptions =
          SharedPreferencesOptions();

      await migrateLegacySharedPreferencesToSharedPreferencesAsyncIfNecessary(
        legacySharedPreferencesInstance: theSpInstance!,
        sharedPreferencesAsyncOptions: sharedPreferencesOptions,
        migrationCompletedKey: 'migrationCompleted',
      );
    }
    return theSpInstance!;
  }
}
